/**
 *
 * 下面是文件上传与结果处理部分
 * @type {Map<any, any>}
 */
//文件上传的MAp
var fileIdMap = new Map();

layui.use('layedit', function () {
    var element = layui.element;

    //获取hash来切换选项卡，假设当前地址的hash为lay-id对应的值
    var layid = location.hash.replace(/^#test1=/, '');
    element.tabChange('test1', layid); //假设当前地址为：http://a.com#test1=222，那么选项卡会自动切换到“发送消息”这一项

    //监听Tab切换，以改变地址hash值
    element.on('tab(test1)', function () {
        location.hash = 'test1=' + this.getAttribute('lay-id');
    });

    /**
     * API TAB切换
     *
     * api-tab是lay-filter
     */
        //触发事件
    var element = layui.element;

    var active = {
        tabAdd: function () {
            var count = $('#div_api_tab').children('ul').children('li').length;
            var newID = getMD5Id();
            if (count < 10) {
                //新增一个Tab项
                element.tabAdd('api-tab', {
                    title: '样例' + (count + 1) + '<span class="layui-badge-dot"></span>'  //用于演示
                    , content: getAnewAPITab(newID)
                    , id: newID//实际使用一般是规定好的id，这里以时间戳模拟下
                })
                layui.form.render();
                layui.element.init();

            }
            else {
                layer.msg('求求你别点了,最多只能打开10个好吧！');
            }
        }
    };

    //取消小红点
    $('.layui-tab-title').click(function () {
        $('.layui-this').children('.layui-badge-dot').remove();
    });

    $('.site-demo-active').on('click', function () {
        var othis = $(this), type = othis.data('type');
        active[type] ? active[type].call(this, othis) : '';
    });

});

layui.use('upload', function () {
    var $ = layui.jquery
        , upload = layui.upload;

    //普通图片上传
    var uploadInst = upload.render({
        elem: '#test1'
        , url: '/upload/'
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#demo1').attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
                return layer.msg('上传失败');
            }
            //上传成功
        }
        , error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });

    //多图片上传
    upload.render({
        elem: '#test2'
        , url: '/upload/'
        , multiple: true
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#demo2').append('<img src="' + result + '" alt="' + file.name + '" class="layui-upload-img">')
            });
        }
        , done: function (res) {
            //上传完毕
        }
    });

    //同时绑定多个元素，并将属性设定在元素上
    upload.render({
        elem: '.demoMore'
        , before: function () {
            layer.tips('接口地址：' + this.url, this.item, {tips: 1});
        }
        , done: function (res, index, upload) {
            var item = this.item;
            console.log(item); //获取当前触发上传的元素，layui 2.1.0 新增
        }
    })


    //拖拽上传
    var uploadDrag = upload.render({
        elem: '#single-file'
        , url: seg_file_upload_path
        , accept: 'file' //普通文件
        , exts: 'txt|doc' //txt
        , size: 4086 //kb
        , before: function (obj) {
            // layer.msg('图片上传中', {
            //     icon: 16
            //     , shade: 0.01
            // });
        }
        , done: function (res) {
            console.log(res)
            //如果正常返回
            if (res.status == 0) {
                showFileSegResult(res);
            }
            else {
                layer.alert('该文件异常，请重新上传', {
                    icon: 2,
                    skin: 'layer-ext-moon'
                })
            }
        }
        , error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadDrag.upload();
            });
        }
    });


    //多文件列表示例
    var demoListView = $('#demoList')
        , uploadListIns = upload.render({
        elem: '#testList'
        , url: seg_file_upload_path
        , accept: 'file'
        , exts: 'txt|doc' //txt
        , multiple: true
        , auto: false
        , bindAction: '#ListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-mini demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-mini layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                demoListView.append(tr);
            });
        }
        , done: function (res, index, upload) {
            //关闭加载层
            layer.closeAll('loading');

            if (res.status == 0) { //上传成功
                var tr = demoListView.find('tr#upload-' + index)
                    , tds = tr.children();
                var thisID = $.trim(getMD5Id());

                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html("<button id=\"" + thisID + "\" class=\"layui-btn layui-btn-mini\" onclick=\"showFileSegResultByID(\'" + thisID + "\')\">查看</button>");
                //将结果用map存储
                fileIdMap.set(thisID, res);
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);

            //关闭加载层
            layer.closeAll('loading');
        }
        , error: function (index, upload) {
            var tr = demoListView.find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            //关闭加载层
            layer.closeAll('loading');
        }
    });


});

//文件上传加载层
function mutifileLoad() {

    layer.load(2);
}

function showFileSegResult(res) {

    for (var i = 0; i < res.data.length; i++) {

        var thisData = res.data[i];
        var tmpStr = "";
        var fileName = thisData.fileName;
        var downloadPath = thisData.download;

        //取出分词的结果
        for (var j = 0; j < thisData.segResult.results.length; j++) {
            for (var i = 0; i < thisData.segResult.results[j].items.length; i++) {
                if (thisData.segResult.results[j].items[i].item == "")
                    continue;
                //取一个唯一id
                var itsId = getMD5Id();
                var posClass = getColorClassName_2(thisData.segResult.results[j].items[i].pos);
                tmpStr += " <div id=" + itsId + "   onmouseenter=\"showTips($(this))\" onmouseleave=\"closeTips()\" class=\"layui-btn layui-btn-primary " + posClass + "\"  style=\"height: 48px;\"><div class=\"result-tips-mes\">" + thisData.segResult.results[j].items[i].item + "</div><div class=\"result-tips-des\">" + thisData.segResult.results[j].items[i].pos + "</div></div>";
            }
        }
        var resStr = "";
        resStr += '<fieldset class="layui-elem-field"><legend>分词信息集合</legend> <div class="layui-field-box"><fieldset class="layui-elem-field layui-field-title"><legend>文件原文</legend><div class="layui-field-box"><blockquote class="layui-elem-quote  layui-quote-nm">' + thisData.txt + '</blockquote></div></fieldset> <fieldset class="layui-elem-field layui-field-title"><legend>分词结果</legend><div class="layui-field-box"></div></fieldset><div class="layui-row"> <div class="layui-col-md12"> <div class="layui-btn-container">' + tmpStr +
            '</div></div></div><fieldset class="layui-elem-field layui-field-title"><legend>结果操作</legend><div class="layui-field-box"><div class="layui-btn-container">' +
            '<a href=/' + downloadPath + ' download=' + fileName + ' class="layui-btn"><i class="layui-icon">&#xe601;</i> 下载文件</a> </div></div><blockquote class="layui-elem-quote">注:本处分词结果以TXT形式保存，词与词之间以空格切分，词后以“/”注明词性。</blockquote></fieldset></div></fieldset>';

        //弹出窗口
        layer.open({
            type: 1,
            title: fileName + '分词结果展示',
            shade: 0,
            maxmin: true,
            skin: 'layui-layer-rim', //加上边框
            area: ['840px', '480px'], //宽高
            content: resStr
        });
    }


}

function showFileSegResultByID(ID) {

    var res = fileIdMap.get(ID);
    if (res == null) {
        layer.alert('该文件异常，请尝试删除并重新上传', {
            icon: 2,
            skin: 'layer-ext-moon'
        });
    }
    else
        showFileSegResult(res);

}

//URL爬取并分词的异步逻辑部分
function crawlAndAnalyze() {

    var regex = /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i;
    var url = $('#input_url').val();
    //正则判断是否是链接
    if (!regex.test(url)) {
        layer.msg('这个不是URL，请检查。', {icon: 5});
        return;
    }
    //判断是否是本站的链接
    if (url.indexOf("/core/") != -1 || url.indexOf("localhost") != -1 || url.indexOf("127.") != -1) {
        layer.msg('这是我的网站，不要这么搞。', {icon: 5});
        return;
    }

    var obj = new Object();
    obj.url = url;
    var requestJson = JSON.stringify(obj);
    var index = layer.load(2);
    //发送异步请求
    jQuery.ajax({
        url: seg_url_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (res) {
        //关闭等待层
        layer.close(index);
        //如果正常返回
        if (res.status == 0) {
            showFileSegResult(res);
        }
        else {
            layer.alert('该网页异常，解析失败', {
                icon: 2,
                skin: 'layer-ext-moon'
            })
        }
    }).fail(function (data) {
        layer.close(index);
        layer.alert("请求失败，原因：" + data.msg, {icon: 2});
    });


}

/**
 * 下面是单文本的异步逻辑部分
 *
 * @type {Set<any>}
 */
//一级词性的集合
var posList = new Set();
//二级词性的集合
var posList_2 = new Set();
//记录上一个被点击的临时变量
var segLastClickTmpID = "temp";

//监听文本框事件
$('#text_main_text').bind('input', function () {
    var before = $('#text_main_text').val();
    TextWordCount(2000, "text_main_text");
    setTimeout(function (args) {
        var after = $('#text_main_text').val();
        if (before == after && after.trim() != '') {
            doTextChange();
        }
    }, 2000);

});


function doTextChange() {

    //还原临时变量
    segLastClickTmpID = "temp";
    //加载等待
    var index = layer.load(2, {shade: 0.25});
    //创建一个js对象
    var requestObj = new Object();
    //获取文本库内容
    var text = $('#text_main_text').val();
    //去空哥
    text = $.trim(text);
    //填充对象信息
    requestObj.text = text;
    requestObj.type = "HANLP_NLP";
    requestObj.filter_sw = false;
    requestObj.filter_p = false;
    // 对象转换为字符串
    var requestJson = JSON.stringify(requestObj);
    // console.log(requestJson);
    requestObj.type = getSegTypeInOrder(0);
    requestJson = JSON.stringify(requestObj);

    //发送异步请求
    jQuery.ajax({
        url: seg_demo_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        //关闭等待层
        layer.close(index);
        //将结果加载到页面中
        loadSegMes(0, data);

    }).fail(function (data) {
        console.log("失败回调");
        layer.close(index);
    });

    requestObj.type = getSegTypeInOrder(1);
    requestJson = JSON.stringify(requestObj);
    //发送异步请求
    jQuery.ajax({
        url: seg_demo_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        //关闭等待层
        layer.close(index);
        //将结果加载到页面中
        loadSegMes(1, data);

    }).fail(function (data) {
        console.log("失败回调");
        layer.close(index);
    });

    requestObj.type = getSegTypeInOrder(2);
    requestJson = JSON.stringify(requestObj);
    //发送异步请求
    jQuery.ajax({
        url: seg_demo_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        //关闭等待层
        layer.close(index);
        //将结果加载到页面中
        loadSegMes(2, data);

    }).fail(function (data) {
        console.log("失败回调");
        layer.close(index);
    });

    requestObj.type = getSegTypeInOrder(3);
    requestJson = JSON.stringify(requestObj);
    //发送异步请求
    jQuery.ajax({
        url: seg_demo_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        //关闭等待层
        layer.close(index);
        //将结果加载到页面中
        loadSegMes(3, data);

    }).fail(function (data) {
        console.log("失败回调");
        layer.close(index);
    });

    requestObj.type = getSegTypeInOrder(4);
    requestJson = JSON.stringify(requestObj);
    //发送异步请求
    jQuery.ajax({
        url: seg_demo_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        //关闭等待层
        layer.close(index);
        //将结果加载到页面中
        loadSegMes(4, data);

    }).fail(function (data) {
        console.log("失败回调");
        layer.close(index);
    });
}

//JSON格式的分词结果加载到html中，并渲染。
function loadSegMes(segName, data) {

    var shouldPutContent = getSegResultTab(segName);
    //清空已有的内容
    shouldPutContent.empty();
    //清空已有的词性栏
    posList.clear();
    posList_2.clear();

    for (var j = 0; j < data.results.length; j++) {
        for (var i = 0; i < data.results[j].items.length; i++) {
            //取一个唯一id
            var itsId = getMD5Id();

            if (i == 0 && j == 0)
                shouldPutContent.append("<div id=" + itsId + " class=\"layui-btn layui-btn-primary\" onclick='clickToshowWordsDetail($(this))' onmouseleave=\"closeTips()\" onmouseenter=\"showTips($(this))\"" +
                    "style=\"margin-left: 10px;margin-top: 10px;height: 48px;\">" +
                    "<div class=\"result-tips-mes\">" + data.results[0].items[0].item + "</div>" +
                    "<div class=\"result-tips-des\">" + data.results[0].items[0].pos + "</div>" +
                    "</div>");
            else
                shouldPutContent.append(" <div id=" + itsId + " onclick='clickToshowWordsDetail($(this))' onmouseenter=\"showTips($(this))\" onmouseleave=\"closeTips()\" class=\"layui-btn layui-btn-primary btn_plus\"  style=\"height: 48px;\"><div class=\"result-tips-mes\">" + data.results[j].items[i].item + "</div><div class=\"result-tips-des\">" + data.results[j].items[i].pos + "</div></div>");

            posList.add(data.results[j].items[i].pos[0]);
            posList_2.add(data.results[j].items[i].pos);
        }
    }

    //执行词性选择栏的加载。
    showPosBar(segName);
    //执行渲染
    layui.form.render();

}


//绑定弹出提示层事件
function showTips(node) {
    var nodeId = '#' + $(node[0]).attr('id');
    var pos = getPosLevel_2($(node[0].lastChild).text());
    layer.tips(pos, nodeId, {
        tips: 3
    });
}

//关闭弹出层事件
function closeTips() {
    layer.closeAll('tips');
}

//点击词汇显示详情事件
function clickToshowWordsDetail(node) {

    var nodeId = '#' + $(node[0]).attr('id');
    if (segLastClickTmpID != 'temp') {
        $("#" + segLastClickTmpID).removeClass('result-seg-selected');
        $($("#" + segLastClickTmpID)[0].lastChild).removeClass('result-seg-pos-selected');
    }

    $(nodeId).addClass('result-seg-selected');
    $(node[0].lastChild).addClass('result-seg-pos-selected');
    segLastClickTmpID = $(node[0]).attr('id');
    //词汇详情展示
    var span_seg_word = $($('.layui-tab-item .layui-show')[0]).find('.span_seg_word');
    var span_seg_pos = $($('.layui-tab-item .layui-show')[0]).find('.span_seg_pos');
    var span_seg_entity = $($('.layui-tab-item .layui-show')[0]).find('.span_seg_entity');
    span_seg_word.text($(node[0].firstChild).text());
    span_seg_pos.text(getPosLevel_1($(node[0].lastChild).text()));
    if ($(node[0].lastChild).text().charAt(0) == 'n')
        span_seg_entity.text(getPosLevel_2($(node[0].lastChild).text()));
    else
        span_seg_entity.text(' ');


}

//词性栏的生成
function showPosBar(segName) {

    var segNameNode = getSegResultTab(segName);

    var posBar = $(segNameNode.parent().parent()).find('.div_pos_bar');
    var nonBar = $(segNameNode.parent().parent()).find('.div_special_non');
    posBar.empty();
    nonBar.empty();
    nonBar.append(" <div class=\"mes-select-title\">专名识别</div>");
    for (var p of posList) {
        var nameOfPos = getPosLevel_1(p);
        posBar.append("<button id='" + p + "_" + segName + "'  class=\"layui-btn layui-btn-primary\" onclick='filterOfPos($(this))'>" + nameOfPos + "</button>");

    }
    for (var p of posList_2) {
        if (p.charAt(0) == 'n' && p.length > 1) {
            var detailNameofPos = getPosLevel_2(p);
            nonBar.append("<button id='" + p + "_" + segName + "'  class=\"layui-btn layui-btn-primary\" onclick='filterOfPos($(this))'>" + detailNameofPos + "</button>");
        }
    }

}

//词性栏的点击后，筛选词性
function filterOfPos(node) {
    var nodeId = $(node[0]).attr('id');
    var className;
    var nodePos = nodeId.split("_")[0];
    className = 'seg-result-pos-filter-' + getColorClassName(nodePos);

    var posBarChildren = $($('.layui-tab-item .layui-show')[0]).find('.div_pos_bar').children();
    for (var i = 0; i < posBarChildren.size(); i++) {
        $(posBarChildren[i]).removeClass();
        $(posBarChildren[i]).addClass('layui-btn layui-btn-primary');
    }
    var nonPosBarChildren = $($('.layui-tab-item .layui-show')[0]).find('.div_special_non').children();
    for (var i = 1; i < nonPosBarChildren.size(); i++) {
        $(nonPosBarChildren[i]).removeClass();
        $(nonPosBarChildren[i]).addClass('layui-btn layui-btn-primary');
    }

    $('#' + nodeId).addClass(className);
    var tabShowId = $($('.layui-tab-item .layui-show')[0]).find('.layui-col-xs10')[0].id;
    console.log(tabShowId);
    var childrenOftab = $('#' + tabShowId).children();
    $(childrenOftab[0]).removeClass();
    $(childrenOftab[0]).addClass('layui-btn layui-btn-primary');
    if ($(childrenOftab[0].lastChild).text().charAt(0) == nodePos || $(childrenOftab[0].lastChild).text() == nodePos) {
        $(childrenOftab[0]).addClass(className);
    }
    for (var i = 1; i < childrenOftab.size(); i++) {
        $(childrenOftab[i]).removeClass();
        $(childrenOftab[i]).addClass('layui-btn layui-btn-primary  btn_plus');
        if ($(childrenOftab[i].lastChild).text().charAt(0) == nodePos || $(childrenOftab[i].lastChild).text() == nodePos) {
            $(childrenOftab[i]).addClass(className);
        }
    }
}

//按顺序获取分词方式
function getSegTypeInOrder(order) {
    switch (order) {
        case 0:
            return "HANLP_NLP";
        case 1:
            return "HANLP_STANDARK";
        case 2:
            return "HANLP_N_SHORTEST";
        case 3:
            return "HANLP_INDEX";
        case 4:
            return "ANSJ_BASIC";
        default:
            return "ANSJ_NLP";
    }
}

//获取不同的分词方式展示的面板
function getSegResultTab(segName) {
    switch (segName) {
        case 0:
            return $('#div_seg_result_nlp');
        case 1:
            return $('#div_seg_result_standark');
        case 2:
            return $('#div_seg_result_dic');
        case 3:
            return $('#div_seg_result_index');
        case 4:
            return $('#div_seg_result_basic');
        default:
            return $('#div_seg_result_nlp');
    }
}


/**
 *
 * 下面是API调用逻辑部分
 **/
//预览要API请求
function previewAPICode(formClassName) {

    //要发送的json对象
    var jsonObj = new Object();
    var tips = "";

    var form = $("." + formClassName);
    var SegType = form.find("select[name=\'segmentType\']").val();
    var sw_key = form.find("select[name=\'segmentTypeIntroduce\']").val();
    var sw_value = form.find("select[name=\'ENABLE_STOPWORD_FILTER\']").val();
    var pu_key = form.find("select[name=\'PunctuationFilterIntroduce\']").val();
    var pu_value = form.find("select[name=\'ENABLE_PUNCTUATION_FILTER\']").val();
    var ct_key = form.find("select[name=\'ENABLE_STOPWORD_FILTER\']").val();
    var ct_value = form.find("input[name=\'CUSTOM_WORDS\']").val();
    var format_key = form.find("select[name=\'FormatIntroduce\']").val();
    var format_value = form.find("select[name=\'FORMAT\']").val();


    var selecter = "." + formClassName;
    var textArray = [];
    var textCount = $(selecter).find('.div_seg_api_text').length;
    var textGroup = $(selecter).find('.div_seg_api_text');
    var countTextNum = 0;
    for (var i = 0; i < textCount; i++) {

        var value = $(textGroup[i]).find('input[name=\'SEG_TEXT\']').val();
        if (value == "")
            continue;
        else {

            countTextNum++;
            var tmp = "";
            var key = "text";
            var obj = new Object();
            tmp = "{\"" + key + "\":\"" + value + "\"}";
            obj = $.parseJSON(tmp);
            textArray.push(obj);
        }
    }


    if (countTextNum == 0) {
        layer.alert("至少也要填一个需要分词的句子呀", {icon: 7});
        return "";
    }


    //处理已取得的属性
    if (SegType == null) {
        SegType = "HANLP_NLP";
        tips += "您未选择分词方式，故使用默认值：<i style=\"color: #FF5722;\">HANLP_NLP</i><br>"
    }
    if (sw_key == null || sw_value == null) {
        sw_key = "stopwords_filter";
        sw_value = "FALSE";
        tips += "您未选择是否激活停用词过滤，故使用默认值：<i style=\"color: #FF5722;\">FALSE</i><br>"
    }
    if (pu_key == null || pu_value == null) {
        pu_key = "punctuation_filter";
        pu_value = "FALSE";
        tips += "您未选择是否激活标点符号过滤，故使用默认值：<i style=\"color: #FF5722;\">FALSE</i><br>"
    }
    if (ct_key == null || ct_value == "") {
        ct_key = "custom_filter";
        ct_value = "";
        tips += "您未填写自定义过滤，故使用默认值：<i style=\"color: #FF5722;\">不过滤</i><br>"
    }
    if (format_key == null || format_value == null) {
        format_key = "format";
        format_value = "JSON";
        tips += "您未选择返回格式，故使用默认值：<i style=\"color: #FF5722;\">JSON</i><br>"
    }
    if ("TRUE" == sw_value) sw_value = true; else sw_value = false;
    if ("TRUE" == pu_value) pu_value = true; else pu_value = false;
    if ("" != ct_value) jsonObj.cunstom_filter = ct_value;

    jsonObj.seg_type = SegType;
    jsonObj.stopwords_filter = sw_value;
    jsonObj.punctuation_filter = pu_value;
    jsonObj.format = format_value;

    jsonObj.text = textArray;

    var jsonStr = JSON.stringify(jsonObj);
    var unformatStr = jsonStr;
    jsonStr = formatJson(jsonStr);

    var selecter = "." + formClassName;
    //放到请求代码框中
    $(selecter).find('.code-request').empty();
    $(selecter).find('.code-request').append(jsonStr);
    $('pre code').each(function (i, block) {
        hljs.highlightBlock(block);
    });

    //显示提示
    if (tips != "")
        layer.alert(tips, {icon: 7});

    return unformatStr;
}

//增加文本
function addAPITextInput(formClassName) {


    if ($('.' + formClassName).find('.div_seg_api_text').length == 3) {
        layer.msg("3个够演示就好啦，别点了求求你");
        return;
    }

    var textGroup = $('.' + formClassName).find('.div_seg_api_text').parent();

    textGroup.append("<div class=\"layui-form-item div_seg_api_text\">" +
        "	<div class=\"layui-input-inline\" style=\"width: 100px;\">" +
        "		<select name=\"TextIntroduce\">" +
        "			<option value=\"\" disabled>分词文本</option>" +
        "			<option value=\"CT_FILTER\" selected=\"\">TEXT</option></select>" +
        "	</div>" +
        "	<div class=\"layui-input-inline\" style=\"width: 76%\">" +
        "		<input type=\"text\" name=\"SEG_TEXT\" lay-verify=\"title\" autocomplete=\"off\" placeholder=\"在这里输入您需要分词的文本，若要多段文本，请点击下面的添加按钮\" class=\"layui-input\" /></div>" +
        "	<div class=\"layui-input-inline\" style=\"width: 120px\">" +
        "		<div class=\"layui-btn-group\">" +
        "			<button type='button' class=\"layui-btn\" onclick='addAPITextInput(\"" + formClassName + "\")'>" +
        "				<i class=\"layui-icon\">&#xe654;</i></button>" +
        "			<button type='button' class=\"layui-btn layui-btn-warm layui-btn\" onclick='deleteAPITextInput(\"" + formClassName + "\",$(this))'>" +
        "				<i class=\"layui-icon\">&#xe640;</i></button>" +
        "		</div>" +
        "	</div>" +
        "</div>");

    layui.form.render();
    layui.element.init();

}


//删除文本
function deleteAPITextInput(formClassName, node) {


    if ($('.' + formClassName).find('.div_seg_api_text').length == 1) {
        layer.msg("你删了这最后1个我怎么演示啊？");
        return;
    }
    node.parent().parent().parent().remove();
    layui.form.render();
    layui.element.init();
}


//发送请求
function sendRequest(formClassName) {

    var requestJson = previewAPICode(formClassName);
    var requestObj = $.parseJSON(requestJson);
    var index = layer.load(2);
    var rFormat = "";
    if (requestObj.format == 'JSON') rFormat = "json";
    else rFormat = "text"
    //发送异步请求
    jQuery.ajax({
        url: seg_api_post_path,
        type: "post",
        data: requestJson,
        dataType: rFormat,
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        //关闭等待层
        layer.close(index);
        var selecter = "." + formClassName;
        if (requestObj.format == 'JSON') {

            if (data.status != 0) {
                layer.alert("请求失败，原因：" + data.msg, {icon: 2});
                return;
            }
            //填充code
            var jsonStr = JSON.stringify(data);

            jsonStr = formatJson(jsonStr);
            $(selecter).find('.code-response').empty();
            $(selecter).find('.code-response').removeClass("xml");
            $(selecter).find('.code-response').removeClass("json");
            $(selecter).find('.code-response').addClass("json");
            $(selecter).find('.code-response').append(jsonStr);
            $('pre code').each(function (i, block) {
                hljs.highlightBlock(block);
            });
        }
        else if (requestObj.format == 'XML') {

            var xmlStr = formatXml(data.toString());
            $(selecter).find('.code-response').empty();
            $(selecter).find('.code-response').removeClass("xml");
            $(selecter).find('.code-response').removeClass("json");
            $(selecter).find('.code-response').addClass("xml");
            $(selecter).find('.code-response').text(xmlStr);
            $('pre code').each(function (i, block) {
                hljs.highlightBlock(block);
            });
        }
        else if (requestObj.format == 'TXT') {
            var textStr = formatXml(data.toString());
            $(selecter).find('.code-response').empty();
            $(selecter).find('.code-response').removeClass("xml");
            $(selecter).find('.code-response').removeClass("json");
            $(selecter).find('.code-response').addClass("xml");
            $(selecter).find('.code-response').text(textStr);
            $('pre code').each(function (i, block) {
                hljs.highlightBlock(block);
            });
        }

    }).fail(function (data) {
        layer.close(index);
        layer.alert("请求失败，原因：" + data.msg, {icon: 2});
    });


}


//获取要新添加的apiTAB内容
function getAnewAPITab(className) {


    return "    <fieldset class=\"layui-elem-field layui-field-title\">" +
        "      <legend>参数填充区域</legend>" +
        "      <div class=\"layui-field-box\">" +
        "        <div class=\"layui-row\">" +
        "          <div class=\"layui-col-md12\">" +
        "            <form class=\"layui-form " + className + "\" action=\"\">" +
        "              <div class=\"layui-form-item\">" +
        "                <div class=\"layui-input-inline\" style=\"width: 100px;\">" +
        "                  <select name=\"method\">" +
        "                    <option value=\"\" disabled>请求方法</option>" +
        "                    <option value=\"post\" selected=\"\">POST</option>" +
        "                    <option value=\"get\" disabled>GET</option>" +
        "                    <option value=\"put\" disabled>PUT</option>" +
        "                    <option value=\"delete\" disabled>DELETE</option></select>" +
        "                </div>" +
        "                <div class=\"layui-input-block\" style=\"width: 91%\">" +
        "                  <input type=\"text\" name=\"SEG_URL\" lay-verify=\"title\" autocomplete=\"off\" placeholder=\"" + seg_api_post_path + "\" class=\"layui-input\" disabled></div>" +
        "              </div>" +
        "              <div class=\"layui-form-item\">" +
        "                <div class=\"layui-input-inline\" style=\"width: 100px;\">" +
        "                  <select name=\"segmentTypeIntroduce\">" +
        "                    <option value=\"\" disabled>分词方法</option>" +
        "                    <option value=\"SegType\" selected=\"\">SegType</option></select>" +
        "                </div>" +
        "                <div class=\"layui-input-block\" style=\"width: 91%\">" +
        "                  <select name=\"segmentType\">" +
        "                    <option value=\"\" disabled>目前系统内置的分词方法</option>" +
        "                    <option value=\"HANLP_NLP\" selected=\"\">HANLP_NLP</option>" +
        "                    <option value=\"ANSJ_NORMAL\">ANSJ_NORMAL</option>" +
        "                    <option value=\"ANSJ_NLP\">ANSJ_NLP</option>" +
        "                    <option value=\"ANSJ_DIC\">ANSJ_DIC</option>" +
        "                    <option value=\"ANSJ_INDEX\">ANSJ_INDEX</option>" +
        "                    <option value=\"ANSJ_BASIC\">ANSJ_BASIC</option>" +
        "                    <option value=\"HANLP_STANDARK\">HANLP_STANDARK</option>" +
        "                    <option value=\"HANLP_INDEX\">HANLP_INDEX</option>" +
        "                    <option value=\"HANLP_N_SHORTEST\">HANLP_SHORTEST</option>" +
        "                    <option value=\"HANLP_CRF\">HANLP_CRF</option>" +
        "                    <option value=\"HANLP_FASTDIC\">HANLP_FASTDIC</option></select>" +
        "                </div>" +
        "              </div>" +
        "              <div class=\"layui-form-item\">" +
        "                <div class=\"layui-input-inline\" style=\"width: 100px;\">" +
        "                  <select name=\"StopwordFilterIntroduce\">" +
        "                    <option value=\"\" disabled>停用词过滤</option>" +
        "                    <option value=\"SW_FILTER\" selected=\"\">SW_FILTER</option></select>" +
        "                </div>" +
        "                <div class=\"layui-input-block\" style=\"width: 91%\">" +
        "                  <select name=\"ENABLE_STOPWORD_FILTER\">" +
        "                    <option value=\"\" disabled>是否开启</option>" +
        "                    <option value=\"TRUE\" selected=\"\">TRUE</option>" +
        "                    <option value=\"FALSE\">FALSE</option></select>" +
        "                </div>" +
        "              </div>" +
        "              <div class=\"layui-form-item\">" +
        "                <div class=\"layui-input-inline\" style=\"width: 100px;\">" +
        "                  <select name=\"PunctuationFilterIntroduce\">" +
        "                    <option value=\"\" disabled>标点过滤</option>" +
        "                    <option value=\"PT_FILTER\" selected=\"\">PT_FILTER</option></select>" +
        "                </div>" +
        "                <div class=\"layui-input-block\" style=\"width: 91%\">" +
        "                  <select name=\"ENABLE_PUNCTUATION_FILTER\">" +
        "                    <option value=\"\" disabled>是否开启</option>" +
        "                    <option value=\"TRUE\" selected=\"\">TRUE</option>" +
        "                    <option value=\"FALSE\">FALSE</option></select>" +
        "                </div>" +
        "              </div>" +
        "              <div class=\"layui-form-item\">" +
        "                <div class=\"layui-input-inline\" style=\"width: 100px;\">" +
        "                  <select name=\"CustomFilterIntroduce\">" +
        "                    <option value=\"\" disabled>自定义过滤</option>" +
        "                    <option value=\"CT_FILTER\" selected=\"\">CT_FILTER</option></select>" +
        "                </div>" +
        "                <div class=\"layui-input-block\" style=\"width: 91%\">" +
        "                  <input type=\"text\" name=\"CUSTOM_WORDS\" lay-verify=\"title\" autocomplete=\"off\" placeholder=\"在这里输入您自定义需要过滤的词汇，以英文小写逗号\',\'分割\" class=\"layui-input\" /></div>" +
        "              </div>" +
        "              <div class=\"layui-form-item\">" +
        "                <div class=\"layui-input-inline\" style=\"width: 100px;\">" +
        "                  <select name=\"FormatIntroduce\">" +
        "                    <option value=\"\" disabled>格式选择</option>" +
        "                    <option value=\"FORMAT\" selected=\"\">FORMAT</option></select>" +
        "                </div>" +
        "                <div class=\"layui-input-block\" style=\"width: 91%\">" +
        "                  <select name=\"FORMAT\">" +
        "                    <option value=\"\" disabled>目前已经支持的返回格式</option>" +
        "                    <option value=\"JSON\" selected=\"\">JSON</option>" +
        "                    <option value=\"XML\">XML</option>" +
        "                    <option value=\"TXT\">TXT</option></select>" +
        "                </div>" +
        "              </div>" +
        "              <div class=\"layui-form-item div_seg_api_text\">" +
        "                <div class=\"layui-input-inline\" style=\"width: 100px;\">" +
        "                  <select name=\"TextIntroduce\">" +
        "                    <option value=\"\" disabled>分词文本</option>" +
        "                    <option value=\"CT_FILTER\" selected=\"\">TEXT</option></select>" +
        "                </div>" +
        "                <div class=\"layui-input-inline\" style=\"width: 76%\">" +
        "                  <input type=\"text\" name=\"SEG_TEXT\" lay-verify=\"title\" autocomplete=\"off\" placeholder=\"在这里输入您需要分词的文本，若要多段文本，请点击下面的添加按钮\" class=\"layui-input\" /></div>" +
        "                <div class=\"layui-input-inline\" style=\"width: 120px\">" +
        "                  <div class=\"layui-btn-group\">" +
        "                    <button type=\'button\' id=\"btn_add_onlyone\" class=\"layui-btn layui-btn\" onclick=\'addAPITextInput(\"" + className + "\")\'>" +
        "                      <i class=\"layui-icon\">&#xe654;</i></button>" +
        "                    <button type=\'button\' id=\"btn_delete_onlyone\" class=\"layui-btn layui-btn-warm layui-btn\" onclick=\'deleteAPITextInput(\"" + className + "\",$(this))\'>" +
        "                      <i class=\"layui-icon\">&#xe640;</i></button>" +
        "                  </div>" +
        "                </div>" +
        "              </div>" +
        "            </form>" +
        "            <fieldset class=\"layui-elem-field layui-field-title\">" +
        "              <legend>执行操作</legend>" +
        "              <div class=\"layui-field-box\">" +
        "                <div class=\"layui-btn-container\">" +
        "                  <button class=\"layui-btn layui-btn-primary\" onclick=\'previewAPICode(\"" + className + "\")\'>" +
        "                    <i class=\"layui-icon\">&#xe62a;</i>预览请求</button>" +
        "                  <button class=\"layui-btn layui-btn-normal\" onclick=\'sendRequest(\"" + className + "\")\'>" +
        "                    <i class=\"layui-icon\">&#xe609;</i>发送请求</button>" +
        "                  <button type=\"reset\" class=\"layui-btn layui-btn-warm\">" +
        "                    <i class=\"layui-icon\">&#xe640;</i>重置请求</button></div>" +
        "              </div>" +
        "            </fieldset>" +
        "            <fieldset class=\"layui-elem-field layui-field-title " + className + "\">" +
        "              <legend>请求预览与分词结果</legend>" +
        "              <div class=\"layui-field-box\">" +
        "                <div class=\"layui-row\">" +
        "                  <div class=\"layui-col-md6\" style=\"min-height: 600px\">" +
        "                    <fieldset class=\"layui-elem-field\">" +
        "                      <legend>请求-REQUEST</legend>" +
        "                      <div class=\"layui-field-box\">" +
        "                        <pre>" +
        "                          <code class=\"json hljs code-request\" style=\"    line-height: 30px; margin-left: 30px;word-wrap: break-word; max-width: 480px; height: 600px;overflow-y: scroll;\"></code>" +
        "                        </pre>" +
        "                      </div>" +
        "                    </fieldset>" +
        "                  </div>" +
        "                  <div class=\"layui-col-md6\" style=\"min-height: 600px;\">" +
        "                    <fieldset class=\"layui-elem-field\">" +
        "                      <legend>响应-RESPONSE</legend>" +
        "                      <div class=\"layui-field-box\">" +
        "                        <pre>" +
        "                          <code class=\"json hlsj code-response\" style=\" line-height: 30px; margin-left: 30px;word-wrap: break-word; max-width: 480px; height: 600px;overflow-y: scroll;\"></code>" +
        "                        </pre>" +
        "                      </div>" +
        "                    </fieldset>" +
        "                  </div>" +
        "                </div>" +
        "              </div>" +
        "            </fieldset>" +
        "          </div>" +
        "        </div>" +
        "      </div>" +
        "    </fieldset>";

}


/**
 *
 * 下面是对用户建议的提交
 *
 */
function handonSuggetions() {

    //prompt层
    layer.prompt({title: '输入您的建议，按确认即提交', formType: 2, value: ' XXXX 是新词汇，请收录。'}, function (text, index) {
        layer.close(index);
        //发起ajax请求
        var obj = new Object();
        obj.words = text;
        obj.type = "新词建议"
        var requestJson = JSON.stringify(obj);
        //发送异步请求
        jQuery.ajax({
            url: seg_suggestion,
            type: "post",
            data: requestJson,
            dataType: "json",
            contentType: "application/json;charset=utf-8"
        }).done(function (data) {
            console.log(data);
            //第三方扩展皮肤
            layer.alert('感谢您的提交，我们会第一时间处理并给您回复。', {
                icon: 6,
                skin: 'layer-ext-moon' //该皮肤由layer.seaning.com友情扩展。关于皮肤的扩展规则，去这里查阅
            })
            layer.close(layerIndex);
        }).fail(function (data) {
            layer.alert("请求失败", {icon: 7});
            layer.close(layerIndex);
        });
    });

}